package com.analysis.interceptor;

import com.analysis.utils.LogUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.springframework.stereotype.Component;

/**
 * 性能监控切面
 * 自动记录方法执行时间和性能指标
 */
@Aspect
@Component
public class PerformanceMonitorAspect {
    
    private static final Logger logger = LogUtils.getLogger(PerformanceMonitorAspect.class);
    
    /**
     * 定义切点：所有Controller方法
     */
    @Pointcut("execution(* com.analysis.controller.*.*(..))")
    public void controllerMethods() {}
    
    /**
     * 定义切点：所有Service方法
     */
    @Pointcut("execution(* com.analysis.services.*.*(..))")
    public void serviceMethods() {}
    
    /**
     * 定义切点：所有Client方法
     */
    @Pointcut("execution(* com.analysis.client.*.*(..))")
    public void clientMethods() {}
    
    /**
     * 环绕通知：记录方法执行时间
     */
//    @Around("controllerMethods() || serviceMethods() || clientMethods()")
    public Object monitorPerformance(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        String methodName = joinPoint.getSignature().getName();
        String className = joinPoint.getTarget().getClass().getSimpleName();
        String fullMethodName = className + "." + methodName;
        
        try {
            // 记录方法进入日志
            LogUtils.enterMethod(logger, fullMethodName, "参数数量", joinPoint.getArgs().length);
            
            // 执行原方法
            Object result = joinPoint.proceed();
            
            // 记录方法退出日志
            LogUtils.exitMethod(logger, fullMethodName, result != null ? "成功" : "无返回值");
            
            // 记录执行时间
            LogUtils.logExecutionTime(logger, fullMethodName, startTime);
            
            return result;
            
        } catch (Exception e) {
            // 记录异常日志
            LogUtils.logException(logger, "方法执行异常: " + fullMethodName, e);
            LogUtils.logExecutionTime(logger, fullMethodName + "(异常)", startTime);
            throw e;
        }
    }
}
